<script>
import axios from "axios";
import {getToken, removeToken, saveToken} from "@/store/token";
import addAddress from "@/components/addAddress.vue";
import updateAddr from "@/components/updateAddr.vue";
import myNav from "@/components/myNav.vue";
import foot from "@/components/foot.vue";
import payment from "@/components/Payment.vue"

export default {
  name: "PayPage",
  components: {foot, myNav, updateAddr, addAddress, payment},
  data() {
    var checkMobile = (rule, value, callback) => {
      const regUser = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
      if (regUser.test(value)) {
        return callback()
      }else {
        if (value.length !== 11) {
          callback(new Error('手机号码长度应该是11位'))
        }
        callback(new Error("手机号格式不正确"))
      }
    }
    return {
      state: {
        order: {
          userId: "",
          address: '',
          ids: '',
          total: 0,
          orderId: ''
        },
        updateForm: {},
        book: [],
        addressId: '',
        addressList: [],
        page: 1,
        size: 2,
        keyword: '',
      },
      hoverIndex: -1, // 菜单hover索引
      activeLinkId: 0, // 当前激活的菜单id
      updateFormVisible: false,
      payVisible: false,
      addFormVisible: false,
      total: 0,
      payment: {
        payment: 'http://localhost:8088/img/1.jpg'
      },
      rules: {
        name: [
          {required: true, message: '请输入收货人', trigger: 'blur'},
          {min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, validator: checkMobile, trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'},
        ]
      }
    }
  },
  methods: {
    getAddress() {
      this.$api.address.getAddress(
          this.state.page,
          this.state.size,
          JSON.parse(getToken("user")).id,
          this.state.keyword
      ).then((res) => {
        var data = res.data;
        if (data.success) {
          this.state.addressList = data.content
          this.state.total = Number(data.total)
        } else {
          this.$message.error(data.message);
        }
      }).catch((resp) => {
        this.$message.error('服务器访问失败' + resp);
      })
    },
    search() {
      this.state.page=1
      this.getAddress()
    },
    payPageChange(val) {
      this.addFormVisible = val
      this.updateFormVisible = val
      this.state.page=1
      this.getAddress()
      if (this.payVisible){
        this.payVisible = val
        removeToken("order")
        this.$router.push("/")
      }
    },
    openEditDialog(item) {
      this.state.updateForm = item;
      this.updateFormVisible = true;
    },
    openAddDialog() {
      this.addFormVisible = true;
    },
    handleCurrentChange() {
      this.getAddress();
    },
    deleteAddress(item) {
      this.$confirm('此操作将永久删除该地址, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.address.deleteAddressById(item.id).then((res) => {
          var data = res.data;
          if (data.success) {
            this.$message.success(data.message)
            this.state.page = 1;
            this.getAddress();
            this.addFormVisible = false
          } else {
            this.$message.error(data.message);
          }
        }).catch((resp) => {
          this.$message.error('服务器访问失败' + resp);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    toCart() {
      this.$router.push("/myCart")
    },
    addOrder() {
      if (this.state.order.userId === '' || this.state.order.address === '') {
        this.$message({
          message: '未选中地址',
          type: 'warning'
        });
      } else {
        var order = {}
        order.userId = this.state.order.userId
        order.ids = this.state.order.ids
        order.num = this.state.book[0].num
        order.year = this.state.book[0].year
        order.startTime = this.state.book[0].startTime
        order.price = this.state.book[0].price
        order.addressId = this.state.order.address.id
        this.$api.order.createOrder(order).then((res) => {
          if (res.data.success) {
            this.$message({
              message: '加入订单成功',
              type: 'success'
            });
            this.$confirm('是否现在去支付?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'info'
            }).then(() => {
              this.state.order.orderId = res.data.content
              this.payVisible = true
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '尽快支付'
              });
            });
            this.dialogTableVisible = false
          } else {
            this.$message.error('加入订单失败');
          }
        }).catch((res) => {
          this.$message.error('访问服务器');
        })
      }
    },
  },
  mounted() {
    let order = this.$route.params.order;
    if (order) {//传递有值就保存
      saveToken("order", order)
      if (JSON.parse(order).length) {
        this.state.book = this.state.book.concat(JSON.parse(order))
      } else {
        this.state.book.push(JSON.parse(order))
      }
    } else {
      //没有值从本地取
      order = getToken("order")
      if (order) {
        this.state.book = this.state.book.concat(JSON.parse(order))
      } else {//否则就是真的没传值
        this.$message.error('没有对应商品id传递');
        this.$router.push("/")
      }
    }
    this.state.book.forEach(b => {
      this.state.order.total += b.total;
      this.state.order.ids = this.state.order.ids.concat(b.periodicalId, ',');
    })
    //this.state.order.ids = this.state.order.ids.slice(0, this.state.order.ids.length - 1)
    this.state.order.userId = JSON.parse(getToken("user")).id;
    this.getAddress()
  }
}
</script>

<template>
  <div>
    <myNav></myNav>
    <div class="container">
      <span>填写并核对订单信息</span>
      <div class="address-cont">
        <div style="font-size: 15px;position:absolute;right: 0;"><span @click="toCart">返回修改购物车</span></div>
        <div style="margin-top: 25px;border-bottom: 1px solid #e5e5e5;display: flex;justify-content: space-between;">
          <span>收货人信息</span><a @click="openAddDialog">新增地址</a></div>
        <div style="display: inline-flex;margin: 10px;">
          <el-input
              v-model="state.keyword"
              placeholder="请输入姓名/手机号/详细地址"
              prefix-icon="el-icon-search"
              style="width: 800px;margin-right: 10px"
              clearable
              @clear="search"
              @keydown.enter.native="search"></el-input>
          <el-button
              icon="el-icon-search"
              type="primary"
              @click="search">
            搜索
          </el-button>
        </div>
        <ul>
          <li
              class="link-item address-list"
              v-for="(addr,index) in  state.addressList"
              :class="{'link-item-active': addr.id === activeLinkId,'link-item-hover':index===hoverIndex}"
              :key="index"
              @mouseover="hoverIndex = index">
            <el-radio style="width: 100px;" size="mini" v-model="state.order.address" :label="addr" border>
              <span v-if="addr.tag">{{ addr.tag }}</span>
              <span v-else>{{ addr.name }}</span>
            </el-radio>
            <div class="address-info">
              <span>{{ addr.name }}</span>
              <el-tooltip class="item" effect="dark" :content="addr.address" placement="bottom">
                <span>{{ addr.address.slice(0, 10) + "..." }}</span>
              </el-tooltip>
              <span>{{ addr.phone }}</span>
            </div>
            <div v-if="hoverIndex===index" style="position: absolute;right: 80px">
              <a @click="openEditDialog(addr)">编辑</a>
              <a @click="deleteAddress(addr)">删除</a>
            </div>
          </li>
          <li>
            <div style="width: 200px; margin: 10px auto 0;">
              <el-pagination
                  @current-change="handleCurrentChange"
                  :current-page.sync="state.page"
                  :page-size="state.size"
                  layout="total, prev, pager, next"
                  :total="state.total">
              </el-pagination>
            </div>
          </li>
        </ul>
        <div class="goods">
          <div style="border-bottom: 1px solid #e5e5e5;">商品信息</div>
          <div class="goods-list">
            <el-table
                :data="state.book"
                style="width: 100%">
              <el-table-column
                  label="商品信息"
                  width="400px"
              >
                <template slot-scope="scope">
                  <div style="display: flex;justify-content:space-around; align-items: center">
                    <el-image style="width: 80px;" :src="scope.row.coverAddress"/>
                    <p>{{ scope.row.name }}</p>
                    <div style="display: flex;flex-direction: column;margin-left: 20px">
                      <span>起刊时间：{{ scope.row.startTime }}</span>
                      <span>购买年数：{{ scope.row.year }}</span>
                      <span>期数：{{ scope.row.periods }}</span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                  prop="price"
                  label="单价(元)"
              >
              </el-table-column>
              <el-table-column
                  prop="num"
                  label="数量(本)"
              >
              </el-table-column>
              <el-table-column
                  label="小计"
              >
                <template slot-scope="scope">
                  <div>
                    <span style="color: #ffaf21;font-weight: bold">￥{{ scope.row.total }}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div style="width: 100%;margin-top: 20px;display: flex;flex-direction: column;align-items: end">
        <div style="float: right;">
          <span style="color: #ffaf21;font-weight: bold">{{ state.book.length }}</span>件商品，总金额：<span>￥{{
            state.order.total
          }}</span>
        </div>
        <div style="width: 100%;height: 80px;margin-top: 40px;background-color: #ffffff;">
          <div style="margin-right: 40px;display: flex;flex-direction: column;align-items: end">
            <span>应付总额：<span style="color: #ff8400;font-weight: bold;font-size: 28px">￥{{
                state.order.total
              }}</span></span>
            <span style="color:#8a8d92;font-size: 14px">
              <span style="margin-right: 15px">地址：{{ state.order.address.address }}</span>
              <span style="margin-right: 10px">收货人：{{ state.order.address.name }}</span>
              <span>{{ state.order.address.phone }}</span>
            </span>
          </div>
        </div>
        <el-button style="margin-top: 10px" type="success" @click="addOrder">提交订单</el-button>
      </div>
      <updateAddr v-if="updateFormVisible" @changeVal="payPageChange"
                  :updateForm="state.updateForm"></updateAddr>
      <addAddress v-if="addFormVisible" @changeVal="payPageChange"></addAddress>
    </div>
    <payment v-if="payVisible" @changeVal="payPageChange" :order-id="state.order.orderId"></payment>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  width: 950px;
  margin-top: 50px;
}

.address-cont {
  position: relative;
  border: 1px solid #e5e5e5;
  padding: 20px 10px;
  margin-top: 10px;
}

.address-list {
  position: relative;
  display: flex;
  height: 30px;
  align-items: center;
  margin-bottom: 10px;
}

.address-info {
  font-size: 13px;
  color: #969896;

}

.address-info span {
  margin-right: 10px
}

.goods {
  margin-top: 40px;
}

.goods-list {
  margin-top: 10px;
}

.link-item-hover {
  background-color: #fcdcdc;
}

.link-item-active {
  color: #fff;
  background-color: #969896;
}

ul {
  padding: 0;
  margin: 0;
  list-style-type: none;
}

a {
  cursor: pointer;
  font-size: 14px;
  color: #3b75f3;
  margin-right: 10px;
}

.el-dropdown-link {
  cursor: pointer;
}
</style>